package com.ww.springboot.boot.thread.study.base.lock.aqs.demo.lock2;

import com.ww.springboot.boot.thread.study.base.lock.aqs.source.MyAbstractQueuedSynchronizer;

public class MyReentrantSync extends MyAbstractQueuedSynchronizer {

    @Override
    protected boolean tryAcquire(int arg) {
        //1.尝试获取锁 成功则直接返回true
        if (compareAndSetState(0, 1)) {
            //当前获取锁的线程 -需要自己赋值 同步队列只会记录等待线程 不会记录当前获取锁的线程 交由用户自定义扩展性更强
            setExclusiveOwnerThread(Thread.currentThread());
            return true;
        }
        if(Thread.currentThread() == super.getExclusiveOwnerThread()){
            return true;
        }
        return false;
    }

    @Override
    protected boolean tryRelease(int arg) {
        //先判断解锁线程是否当前获取锁的线程
        if(Thread.currentThread() != super.getExclusiveOwnerThread()){
            throw new IllegalMonitorStateException();
        }
        if (compareAndSetState(1, 0)) {
            return true;
        }
        return false;
    }

    public ConditionObject conditionObject() {
        return new ConditionObject();
    }
}